package com.wyp.didishige.fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.utils.DistanceUtil;
import com.wyp.didishige.activity.NewDynamicActivity;
import com.wyp.didishige.config.Config;
import com.wyp.didishige.R;
import com.wyp.didishige.activity.MainActivity;
import com.wyp.didishige.activity.UserInfoActivity;
import com.wyp.didishige.adapter.NearBoyAdapter;
import com.wyp.didishige.model.User;
import com.wyp.didishige.utils.IntentUtil;
import com.wyp.didishige.utils.PreferenceHelper;
import com.wyp.didishige.wiget.xlist.XListView;

import java.util.ArrayList;
import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.datatype.BmobGeoPoint;
import cn.bmob.v3.listener.FindListener;

/**
 * 附近的boy
 */
public class NearBoyFragment extends FragmentBase implements View.OnClickListener, XListView.IXListViewListener {

    private static final String ARG_SECTION_NUMBER = "section_number";

    BmobGeoPoint geoPoint;
    // 定位相关
    LocationClient mLocClient;
    public MyLocationListenner myListener = new MyLocationListenner();

    String uid = null;

    List<User> nearList;
    private static final String USER = "user";

    XListView nearby_list;
    User user;
    NearBoyAdapter nearBoyAdapter;

    Button new_dynamic;

    public static NearBoyFragment newInstance(int sectionNumber) {
        NearBoyFragment fragment = new NearBoyFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);
        fragment.setArguments(args);

        return fragment;
    }

    public NearBoyFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_nearby, container, false);
        nearby_list = (XListView) rootView.findViewById(R.id.nearby_list);

        user = userManager.getCurrentUser(User.class);

        uid = PreferenceHelper.readString(getActivity(), getActivity().getPackageName(), "uid", null);
        new_dynamic = (Button) rootView.findViewById(R.id.new_dynamic);
        new_dynamic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                IntentUtil.start_activity(getActivity(), NewDynamicActivity.class);
            }
        });
        initListView();
        getLocation();
        return rootView;
    }

    private void initListView() {
        nearby_list.setPullRefreshEnable(true);
        nearby_list.setPullLoadEnable(true);
        nearby_list.setXListViewListener(this);
        nearBoyAdapter = new NearBoyAdapter(getActivity(), new ArrayList<User>());

        nearby_list.setAdapter(nearBoyAdapter);

        nearby_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Bundle bundle;
                bundle = new Bundle();
                User boy = (User) nearBoyAdapter.getItem(--position);
                bundle.putString("from", "male");
                bundle.putString("username", boy.getUsername());
                bundle.putString(Config.KEY_USER_ID, boy.getObjectId());
                IntentUtil.start_activity(getActivity(), UserInfoActivity.class, bundle);
            }
        });
    }

    /**
     * 定位
     */
    private void getLocation() {
        // 定位初始化
        mLocClient = new LocationClient(getActivity());
        mLocClient.registerLocationListener(myListener);
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true);// 打开gps
        option.setCoorType("bd09ll"); // 设置坐标类型
//        option.setScanSpan(2000);
        mLocClient.setLocOption(option);
        mLocClient.start();
    }

    /**
     * 定位SDK监听函数
     */
    public class MyLocationListenner implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            if (location != null) {
                geoPoint = new BmobGeoPoint(location.getLongitude(), location.getLatitude());
            } else {
                // 无定位数据默认北京中心
                double cLat = 39.909230;
                double cLon = 116.397428;
                geoPoint = new BmobGeoPoint(cLon, cLat);
            }

            //更新当前位置
            ((MainActivity) getActivity()).refreshPoint(geoPoint);
            User user = userManager.getCurrentUser(User.class);

            if (user != null) {
                user.setCity(location.getCity());
                user.setLocation(geoPoint);
                user.update(getActivity());
            }
            nearby_list.startLoadMore();
        }

        public void onReceivePoi(BDLocation poiLocation) {
        }
    }

    @Override
    public void onClick(View v) {

    }

    int page = 0;
    int limit = 20;

    private void getNearByList() {
        BmobQuery<User> query = new BmobQuery<User>();
        query.addWhereWithinKilometers("location", geoPoint, 3000);
        query.include("rating");
        query.addWhereEqualTo("sex", true);
        query.setLimit(limit);
        query.setSkip(limit * page);
        query.order("-lastLogin");
//        query.include("shiGeObject");
        query.findObjects(getActivity(), new FindListener<User>() {
            @Override
            public void onSuccess(List<User> users) {
                nearList = users;
                if (users != null && users.size() != 0) {
                    LatLng ll;
                    for (User info : nearList) {
                        BmobGeoPoint point = info.getLocation();
                        if (point == null) continue;
                        ll = new LatLng(point.getLatitude(), point.getLongitude());
                        int meter = (int) DistanceUtil.getDistance(ll, new LatLng(geoPoint.getLatitude(), geoPoint.getLongitude()));
                        info.setMeter(meter);
                    }
                    page++;
                    nearBoyAdapter.addAll(users);
                }
            }

            @Override
            public void onFinish() {
                nearby_list.stopLoadMore();
            }

            @Override
            public void onError(int i, String s) {
                ShowToast(s);
            }
        });
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onResume() {
        super.onResume();
        user = userManager.getCurrentUser(User.class);
    }

    @Override
    public void onDestroy() {
        mLocClient.stop();

        super.onDestroy();
    }

    @Override
    public void onRefresh() {

    }

    @Override
    public void onLoadMore() {
        getNearByList();
    }


}

